package appapi.service.impl;

import appapi.Request.EquiPageReq;
import appapi.Request.SelfcheckPageReq;
import appapi.Vo.AddSelfcheckRecVo;
import appapi.Vo.EditSelfcheckDetailVo;
import appapi.Vo.EditSelfcheckRecVo;
import appapi.Vo.SelfcheckDetailVo;
import appapi.Vo.basic.ExcelSelfcheckVo;
import appapi.Vo.record.InspectWarnVo;
import appapi.dao.*;
import appapi.dao.RectificationMapper;
import appapi.dao.SelfcheckMapper;
import appapi.dao.SelfcheckdetailMapper;
import appapi.dao.SelfcheckitemMapper;
import appapi.dto.AnnexType;
import appapi.dto.DelSelfCheckDto;
import appapi.entity.Zhongjiao.AnnexDto;
import appapi.entity.Zhongjiao.SelfcheckDto;
import appapi.entity.app.AnnexEntity;
import appapi.entity.app.RectificationEntity;
import appapi.entity.app.SelfcheckDetailEntity;
import appapi.entity.basic.SelfcheckItemEntity;
import appapi.entity.basic.UserInfo;
import appapi.service.ISelfcheckService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author djq
 * @date 2023/5/17 15:41
 * @description:
 */
@Component
public class SelfcheckServiceImpl implements ISelfcheckService {
    @Resource
    private SelfcheckMapper selfcheckMapper;
    @Resource
    private SelfcheckitemMapper selfcheckitemMapper;
    @Autowired
    private SelfcheckdetailMapper selfcheckdetailMapper;
    @Autowired
    private RectificationMapper rectificationMapper;
    @Resource
    AnnexMapper annexMapper;
    @Resource
    StaffMapper staffMapper;
    @Resource
    EquipmentMapper equipmentMapper;

    @Override
    public List<Map<String, Object>> SelectSelfcheckPage(SelfcheckPageReq selfcheckPageReq) {

        PageHelper.startPage(selfcheckPageReq.getCurrPage(), selfcheckPageReq.getPageSize());

        return selfcheckMapper.selectPage(selfcheckPageReq);
    }

    @Override
    public List<Map<String, Object>> SelectSelfcheckList(Long equipId) {

        return selfcheckMapper.selectSelfcheckList(equipId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int InsertSelfcheck(AddSelfcheckRecVo vo) {

        SelfcheckDto dto = vo.vo2Entity();
        //添加自检记录
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        dto.setSelfState(0);
        int iRet = selfcheckMapper.insertSelective(dto);
        if (iRet > 0) {
            Long selfId = dto.getSelfId();
            //获取自检记录ID
            List<SelfcheckDetailEntity> detailEntityList = new ArrayList<>();
            //整改记录
            List<RectificationEntity> rectList = new ArrayList<>();
            StringBuffer strB = new StringBuffer();
            for (SelfcheckDetailVo detailVo : vo.getDetail()
            ) {
                SelfcheckDetailEntity entity = new SelfcheckDetailEntity();
                entity.setSelfId(selfId);
                entity.setCreateTime(LocalDateTime.now());
                entity.setUpdateTime(LocalDateTime.now());
                entity.setImgurl(String.join(",", detailVo.getImgurlList()));
                entity.setAuditState(0);
                entity.setSelfRequire(detailVo.getSelfRequire());
                entity.setSelfDesc(detailVo.getSelfDesc());
                entity.setSelfResult(detailVo.getSelfResult());
                entity.setSelfItem(detailVo.getSelfItem());
                detailEntityList.add(entity);

                if (detailVo.getSelfResult() == 1) {
                    strB.append(detailVo.getSelfItem() + " ");
                }
            }
            if (detailEntityList.size()>0) {
                //添加自检明细
                selfcheckdetailMapper.insertBatch(detailEntityList);
            }
            //是否需要写整改
            List<String> expList = vo.getDetail().stream()
                    .filter(SelfcheckDetailVo -> SelfcheckDetailVo.getSelfResult() == 1)
                    .map(SelfcheckDetailVo::getSelfItem)
                    .collect(Collectors.toList());
            if (expList.size() > 0) {
                //异常，添加整改信息
                RectificationEntity rectEntity = new RectificationEntity();
                rectEntity.setRectItem(strB.toString());
                rectEntity.setRectRequire(vo.getExpRequire());
                rectEntity.setEquipId(vo.getEquipId());
                rectEntity.setRectState(0);
                rectEntity.setRectAdd(1);
                rectEntity.setRectSource(selfId);
                rectEntity.setRectType(AnnexType.AnnexTypeEnum.selfCheck.getCode());
                //rectEntity.setSoutOper();
                rectEntity.setRectDate(new Date());
                rectEntity.setCreateTime(LocalDateTime.now());
                rectEntity.setUpdateTime(LocalDateTime.now());
                rectList.add(rectEntity);
            }
            //添加整改信息
            if (rectList.size() > 0) {
                rectificationMapper.insertBatch(rectList);
            }

            //有附件则新增附件
            if (vo.getAnnexUrl().size() > 0) {
                //暂搁置
                //String[] user = JwtUtil.getUserInfoByJwtToken(request);
                List<AnnexEntity> annexCollect = vo.getAnnexUrl().stream().map(annex -> {
                    AnnexEntity annexEntity = new AnnexEntity();
                    annexEntity.setCreateTime(LocalDateTime.now());
                    annexEntity.setUpdateTime(LocalDateTime.now());
                    annexEntity.setAnnexTitle("自检");
                    annexEntity.setSecId((dto.getSelfId()));;
                    annexEntity.setAnnexType(AnnexType.AnnexTypeEnum.selfCheck.name());
                    annexEntity.setAnnexUrl(annex);
                    annexEntity.setCreateUser(vo.getCreateUser());
                    return annexEntity;
                }).collect(Collectors.toList());
                annexMapper.insertList(annexCollect);
            }
        }
        return iRet;
    }


    @Override
    public int UpdateSelfcheck(EditSelfcheckRecVo vo) {

        List<Long> selfId = new ArrayList<>();
        selfId.add(vo.getSelfId());
        //验证是否允许编辑删除
        int iRet = rectificationMapper.allowEdit(AnnexType.AnnexTypeEnum.selfCheck.getCode(), selfId);
        if (iRet > 0) {
            return -1;
        } else {
            //添加自检记录
            SelfcheckDto dto = vo.vo2Entity();
            dto.setCreateTime(LocalDateTime.now());
            dto.setUpdateTime(LocalDateTime.now());
            dto.setSelfState(0);
            iRet = selfcheckMapper.updateByPrimaryKeySelective(dto);
            if (iRet > 0) {
                //删除自检明细
                selfcheckdetailMapper.deleteBySelfId(dto.getSelfId());
                //删除整改明细
                rectificationMapper.deleteByRecId(AnnexType.AnnexTypeEnum.selfCheck.getCode(), dto.getSelfId());
                //获取自检记录ID
                List<SelfcheckDetailEntity> detailEntityList = new ArrayList<>();
                //整改记录
                List<RectificationEntity> rectList = new ArrayList<>();
                StringBuffer strB = new StringBuffer();
                for (EditSelfcheckDetailVo detailVo : vo.getDetail()
                ) {
                    SelfcheckDetailEntity entity = new SelfcheckDetailEntity();
                    entity.setSelfId(dto.getSelfId());
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    entity.setImgurl(detailVo.getImgurl());
                    entity.setAuditState(0);
                    entity.setSelfDesc(detailVo.getSelfDesc());
                    entity.setSelfResult(detailVo.getSelfResult());
                    entity.setSelfItem(detailVo.getSelfItem());
                    detailEntityList.add(entity);
                    if (detailVo.getSelfResult() == 1) {
                        strB.append(detailVo.getSelfItem() + " ");
                    }
                }
                if (strB.toString().length() > 0) {
                    //异常，添加整改信息
                    RectificationEntity rectEntity = new RectificationEntity();
                    rectEntity.setRectItem(strB.toString());
                    rectEntity.setRectRequire(vo.getExpRequire());
                    rectEntity.setEquipId(vo.getEquipId());
                    rectEntity.setRectState(0);
                    rectEntity.setRectAdd(1);
                    rectEntity.setRectSource(dto.getSelfId());
                    rectEntity.setRectType(AnnexType.AnnexTypeEnum.selfCheck.getCode());
                    rectEntity.setRectDate(new Date());
                    rectEntity.setCreateTime(LocalDateTime.now());
                    rectEntity.setUpdateTime(LocalDateTime.now());
                    rectList.add(rectEntity);
                }
                //添加自检明细
                if (detailEntityList.size() > 0) {
                    selfcheckdetailMapper.insertBatch(detailEntityList);
                }
                //添加整改信息
                if (rectList.size() > 0) {
                    rectificationMapper.insertBatch(rectList);
                }

            }
            annexMapper.deleteByRecId(AnnexType.AnnexTypeEnum.selfCheck.name(),selfId);
            //有附件则新增附件
            if (vo.getAnnexUrl().size() > 0) {
                //暂搁置
                //String[] user = JwtUtil.getUserInfoByJwtToken(request);
                List<AnnexEntity> annexCollect = vo.getAnnexUrl().stream().map(annex -> {
                    AnnexEntity annexEntity = new AnnexEntity();
                    annexEntity.setCreateTime(LocalDateTime.now());
                    annexEntity.setUpdateTime(LocalDateTime.now());
                    annexEntity.setAnnexTitle("自检");
                    annexEntity.setRecId(dto.getSelfId());
                    annexEntity.setAnnexType(AnnexType.AnnexTypeEnum.selfCheck.name());
                    annexEntity.setAnnexUrl(annex);
                    annexEntity.setCreateUser(vo.getCreateUser());
                    return annexEntity;
                }).collect(Collectors.toList());

                annexMapper.insertList(annexCollect);
            }

        }
        return iRet;
    }

    @Override
    public int DelSelfcheck(DelSelfCheckDto dto) {
        //验证是否允许编辑删除
        int iRet = rectificationMapper.allowEdit(AnnexType.AnnexTypeEnum.selfCheck.getCode(), dto.getSelfId());
        if (iRet > 0) {
            return -1;
        } else {
            //删除自检记录
            iRet = selfcheckMapper.deleteBatch(dto.getSelfId());
            if (iRet > 0) {
                //删除自检明细
                selfcheckdetailMapper.deleteBySelfIds(dto.getSelfId());
                //删除整改明细
                rectificationMapper.deleteSourcesBatch(AnnexType.AnnexTypeEnum.selfCheck.getCode(), dto.getSelfId());
            }
            return iRet;
        }
    }

    @Override
    public List<SelfcheckItemEntity> selectSelfItemByEquipType(Long equipTypeId) {
        List<SelfcheckItemEntity> vo = selfcheckitemMapper.selectItemByTypeId(equipTypeId);
        return vo;
    }

    @Override
    public InspectWarnVo GetWarn(UserInfo userInfo) {
        InspectWarnVo vo = new InspectWarnVo();
        //拿到该人员的信息
        Map<String, Object> staffInfo = staffMapper.selectStaffDetail(userInfo.getUserid());
        EquiPageReq req = new EquiPageReq();
        req.setOrgaPathIds(staffInfo.get("orgaPathIds").toString());
        //查到该人员能看到的所有设备
        List<Map<String, Object>> list = equipmentMapper.selectEquiPageList(req);

        List<Long> equipIds = list.stream().map(map -> (Long) map.get("equipId")).collect(Collectors.toList());

        //拿到本月进行过巡检的数据
        List<Map<String, Object>> monthInfos = selfcheckMapper.selectListByMonth(equipIds);

        vo.setEquipNum(list.size());
        vo.setCheckNum(monthInfos.size());
        vo.setNotCheckNum(vo.getEquipNum() - vo.getCheckNum());
        return vo;
    }

    @Override
    public List<ExcelSelfcheckVo> getList(SelfcheckPageReq req) {
        List<ExcelSelfcheckVo> list = selfcheckMapper.SelfRecExport(req);
        return list;
    }

    @Override
    public SelfcheckDto getSelfCheckModel(Long selfId) {
        SelfcheckDto dto = new SelfcheckDto();
        dto = selfcheckMapper.selectByPrimaryKey(selfId);
        List<SelfcheckDetailEntity> detailEntities = selfcheckdetailMapper.selectBySelfId(selfId);
        dto.setDetail(detailEntities);
        List<AnnexDto> annexDtos = annexMapper.selectAllByRecId(AnnexType.AnnexTypeEnum.selfCheck.name(), selfId);
        dto.setAnnexUrl(annexDtos.stream().map(AnnexDto::getAnnexUrl).collect(Collectors.toList()));
        return dto;
    }
}
